/* testpipe.c - testpipe, produce, consume */

#include <xinu.h>
#include <mips.h>
#include <string.h>
#include <stdio.h>

void produce(void);
void consume(void);
pid32 producerid;		/* ID of producer process	*/
pid32 consumerid;		/* ID of comsumer process	*/
pipid32 pipid_test;		/* ID of pipe used		*/
uint32 N = 10;			/* Lines to display each time	*/
struct pipent *piptr_test;	/* ptr to pipe's table entry	*/

/*--------------------------------------------------------------------------
 *  testpipe  -  use producer and consumer processes to test pipe mechanism
 *--------------------------------------------------------------------------
 */
void	testpipe(void)
{
	printf("Welcome! Please press Enter to test the Producer and Consumer processes.\n");
	pipid_test = pipcreate();
	piptr_test = &piptab[pipid_test];
	producerid = create(produce, 1024, 20, "producer", 0);
	consumerid = create(consume, 1024, 20, "consumer", 0);
	
	pipconnect(pipid_test, producerid, consumerid);
	resume(producerid);
	resume(consumerid);
	pipdisconnect(pipid_test);
	pipdelete(pipid_test);
}

void	produce(void) {
		char pstring[] = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
		uint32 pstring_len;	/* length of text to be written	*/
		pstring_len = strnlen(pstring, 10000);
		pipwrite(pipid_test, pstring, pstring_len,0);
}

void	consume(void) {
		char cstring[100];		/* where to put the read buf	*/
		char ifquit;		/* user's intent to continue	*/
		int32 j;
		int32 countread;
		int32 beginread = 0;

		for(j = 0; j < strnlen(cstring, 10000);j++) {
			cstring[j] = ' ';
		}
		
		ifquit = getchar();
		while(ifquit == '\n') {
			countread = pipread(pipid_test, cstring, N, beginread);
			for(j = 0; j < N; j++) {
				putchar(cstring[j]);
				putchar('\n');
			}
			beginread = beginread + countread;
			printf("\nPress ENTER to continue or press q to quit\n");
			ifquit = getchar();
		}
		if (ifquit == 'q') {
			kill( producerid );
			kill( consumerid );
		}
}
